
--[[
title: ToolBase
description: 基类
]]

local ToolBase = commonlib.inherit(nil, {});

local __event_emitter__ = commonlib.EventEmitter:new();

function ToolBase:ctor()
end

-- 属性 setter getter
function ToolBase:Property(fieldname, default_value, getter, setter)
	local fieldkey = "__field_" .. fieldname .. "__";
	
	self[fieldkey] = default_value;

	getter = getter or ("Get" .. fieldname);
	setter = setter or ("Set" .. fieldname);

	self[getter] = function(self)
		return self[fieldkey];
	end

	self[setter] = function(self, value)
		self[fieldkey] = value;
	end
end 

-- 对象事件机制
-- 触发事件
function ToolBase:TriggerEventCallBack(event_name, ...)
	__event_emitter__:TriggerEventCallBack(tostring(self) .. "_" .. tostring(event_name), ...)
end
-- 监听事件
function ToolBase:RegisterEventCallBack(event_name, class, func)
	if (type(func) ~= "function") then return end
	local key = "__event_callback" .. "_" .. tostring(event_name) .. "_" .. tostring(callback) .. "_" .. tostring(func) .. "__";
	self[key] = function(...)
		if (class) then
			func(class, ...);
		else
			func(...);
		end	
	end
	__event_emitter__:RegisterEventCallBack(tostring(self) .. "_" .. tostring(event_name), self[key]);
end

-- 移除事件
function ToolBase:RemoveEventCallBack(event_name, class, func)
	if (type(func) ~= "function") then return end
	local key = "__event_callback" .. "_" .. tostring(event_name) .. "_" .. tostring(callback) .. "_" .. tostring(func) .. "__";
	__event_emitter__:RemoveEventCallBack(tostring(self) .. "_" .. tostring(event_name), self[key]);
end

-- 单例模式
local function ctor_recursive(o, current_class)
	current_class = current_class or o;
	if(current_class._super) then
		ctor_recursive(o, current_class._super);
	end
	local ctor = rawget(current_class, "ctor");
	if(type(ctor) == "function") then
		ctor(o);
	end
end

function ToolBase:InitSingleton()
	if(not rawget(self, "singletonInited")) then
		self.singletonInited = true;
		ctor_recursive(self);
		self.new = nil;
	end
	return self;
end

commonlib.ToolBase = ToolBase;
return ToolBase;
--[[
local A = commonlib.inherit(ToolBase, {});
A:Property("Key", "hello");

print(A:GetKey());
A:SetKey("world");
print(A:GetKey());
]]

